#include "app_sub_can.h"
#include "bsp_can.h"
#include "bsp_gpio.h"
#include <stdbool.h>
#include <string.h>
#include "main.h"
#include "bsp.h"
#include "app_rs485.h"
#include "app_eeprom.h"

APP_sub_can_t subCan;

static osTimeCost_T pTimecost1[3] = {0};

static void TxSubMes01(void)
{
	subCan.txMes1.mes.life++;

	dv_CAN.fwrite_data(EM_CAN_0,0x0900BCF1, subCan.txMes1.data, 64);
}

static void TXSubMes(void)
{
	static uint16_t step = 0;
	step++;
	switch (step)
	{
		case 1:
			TxSubMes01();
			step = 0;
			break;
		default:
			break;
	}
}
typedef struct 
{
	uint8_t ch;
	uint8_t st;
}rx_io_state_t;


void app_sub_can_rx_run(void)
{
	if(dv_CAN.sub_receive_mes1_flag == SET)
	{
		dv_CAN.sub_receive_mes1_flag = RESET;
		memcpy(subCan.rxMes1.data,dv_CAN.sub_receive_mes1_message.rx_data,64);
		
		subCan.ctrl_type = subCan.rxMes1.mes.ctrl_type;
		if(subCan.ctrl_type == EM_CTRL_TYPE_IO)
		{
			subCan.io_ch = subCan.rxMes1.mes.io_ch;
			subCan.io_st = subCan.rxMes1.mes.io_st;
		}
		else if(subCan.ctrl_type == EM_CTRL_TYPE_485 && subCan.rxMes1.mes.u8485testen == 1)
		{
			rs485.test_en = true;
		}
		else if(subCan.ctrl_type == EM_CTRL_TYPE_balvol)
		{
			if(subCan.rxMes1.mes.batvoltesten == 1)
			{
				subCan.io_ch = EM_IO_BP;
				subCan.io_st = EM_IO_H;
			}
			else
			{
				subCan.io_ch = EM_IO_BP;
				subCan.io_st = EM_IO_L;
			}
		}	
		else if(subCan.ctrl_type == EM_CTRL_TYPE_loadvol)
		{
			if(subCan.rxMes1.mes.loadvoltesten == 1)
			{
				subCan.io_ch = EM_IO_LP;
				subCan.io_st = EM_IO_H;
			}
			else
			{
				subCan.io_ch = EM_IO_LP;
				subCan.io_st = EM_IO_L;
			}
		}
		else if(subCan.ctrl_type == EM_CTRL_TYPE_eep)
		{
			if(subCan.rxMes1.mes.eeptesten == 0x01)//写测试
			{
				eep.test_w_en = true;
			}
			else if(subCan.rxMes1.mes.eeptesten == 0x02)//读测试
			{
				eep.test_r_en = true;
			}
		}
	}
}

void app_sub_can_tx_run(void)
{
	TXSubMes();
}
